package com.photoeditor.demo.ui.fragement;

import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * @author lyzirving
 * time        2018/10/29
 * email       lyzirving@sina.com
 * information
 */

public class ItemClickSupport {

    public interface OnItemClickListener {
        void onItemClick(RecyclerView recyclerView, View view, int position, long itemId);
    }

    public interface OnItemLongClickListener {
        boolean onItemLongClick(RecyclerView recyclerView, View view, int position, long id);
    }

    private RecyclerView mRecyclerView;
    private OnItemClickListener mOnItemClickListener;
    private RecyclerView.Adapter mAdapter;
    private OnItemLongClickListener mOnItemLongClickListener;

    public ItemClickSupport(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
        this.mRecyclerView = recyclerView;
        this.mAdapter = adapter;
    }

    public ItemClickSupport(RecyclerView recyclerView, RecyclerView.Adapter adapter, OnItemClickListener listener) {
        this.mRecyclerView = recyclerView;
        this.mAdapter = adapter;
        mOnItemClickListener = listener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        if (null != onItemClickListener) {
            this.mOnItemClickListener = onItemClickListener;
        }
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        if (null != onItemLongClickListener) {
            this.mOnItemLongClickListener = onItemLongClickListener;
        }
    }

    public void onItemClick(View v) {
        if (null != mRecyclerView && null != mAdapter && null != mOnItemClickListener) {
            try {
                final int position = mRecyclerView.getChildLayoutPosition(v);
                long itemId = mAdapter.getItemId(position);
                mOnItemClickListener.onItemClick(mRecyclerView, v, position, itemId);
            } catch (Exception e) {
                mOnItemClickListener.onItemClick(mRecyclerView, v, 0, 0);
            }
        }
    }

    public boolean onItemLongClick(View v) {
        if (null != mRecyclerView && null != mAdapter && null != mOnItemLongClickListener) {
            final int position = mRecyclerView.getChildLayoutPosition(v);
            final long id = mAdapter.getItemId(position);

            return mOnItemLongClickListener.onItemLongClick(mRecyclerView, v, position, id);
        }

        return false;
    }

}
